﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;

namespace Service.Framework.Utils
{
    public class CustomContractResolver : CamelCasePropertyNamesContractResolver
    {
        /// <summary>
        /// 实现首字母小写
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        protected override string ResolvePropertyName(string propertyName)
        {
            return propertyName.Substring(0, 1).ToLower() + propertyName.Substring(1);
        }

        /// <summary>
        /// 对长整型做处理
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        protected override JsonConverter ResolveContractConverter(Type objectType)
        {
            if (objectType == typeof(long))
            {
                return new JsonConverterLong();
            }
            if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
            {
                return new JsonConverterDatetime();
            }
            return base.ResolveContractConverter(objectType);
        }

        /// <summary>
        /// 创建属性
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="memberSerialization">序列化成员</param>
        /// <returns></returns>
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var test = type.GetMembers().Where(it => it.MemberType == MemberTypes.Field || it.MemberType == MemberTypes.Property).ToList();
            var member = type.GetMembers().Where(it => it.MemberType == MemberTypes.Field || it.MemberType == MemberTypes.Property)
                .Select(it =>
               {
                   var jsonProperty = base.CreateProperty(it, memberSerialization);
                   jsonProperty.ValueProvider = new NullToDefaultMemberValueProvider(it);
                   return jsonProperty;
               }).ToList();

            member = member.Distinct().ToList();

            return member;
            //var fileds = type.GetFields().Select(c =>
            //{
            //    var jsonProperty = base.CreateProperty(c, memberSerialization);
            //    jsonProperty.ValueProvider = new NullToDefaultFiledValueProvider(c);
            //    return jsonProperty;
            //}).ToList();

            //var properties = type.GetProperties().Select(c =>
            //{
            //    var jsonProperty = base.CreateProperty(c, memberSerialization);
            //    jsonProperty.ValueProvider = new NullToDefaultPropertyValueProvider(c);
            //    return jsonProperty;
            //}).ToList();
            //return fileds.Concat(properties).ToList();
        }
    }

}
